﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mes_app_control
{

    public partial class Control_commd_jiatie_Form : Form
    {
        int parent_id;
        private ControlCommandDal controlCommandDal = new ControlCommandDal();
        private MillWrapper millWrapper = new MillWrapper();
        public Control_commd_jiatie_Form(int parent_id)
        {
            InitializeComponent();
            this.parent_id = parent_id;
            this.Load += Control_commd_diao_Form_Load;
        }


        void Query(int parent_id)
        {
            ControlCommand controlCommand = controlCommandDal.Get(parent_id);
            TextBox_machine_no.Text = controlCommand.machine_no;
            TextBox_machine_name.Text = controlCommand.machine_name;
            TextBox_machine_address.Text = controlCommand.machine_address;
            TextBox_command_param.Text = controlCommand.command_param;
            ComboBox_supplier_no.Text = setSupplierName(controlCommand.supplier_no);
            TextBox_command_value.Text = controlCommand.command_value;
            TextBox_description.Text = controlCommand.description;
            TextBox_machine_port.Text = controlCommand.machine_port.ToString();
            TextBox_cnc_num.Text = controlCommand.cnc_num.ToString();

        }

        private string setSupplierNo(string supplierName)
        {
          string result = "";
          if (supplierName == "迪奥")
                result = "diao";

            if (supplierName == "佳铁")
                result = "jiatie";

            return result;
        }


        private string setSupplierName(string supplierNo)
        {
            string result = "";
            if (supplierNo == "diao")
                result = "迪奥";

            if (supplierNo == "jiatie")
                result = "佳铁";

            return result;
        }

        private void Button_save_Click(object sender, EventArgs e)
        {
        if (parent_id == 0)
        { 
        if (controlCommandDal.Add(new ControlCommand()
        {
            machine_no = TextBox_machine_no.Text,
            machine_name = TextBox_machine_name.Text,
            machine_address = TextBox_machine_address.Text,
            command_param = TextBox_command_param.Text,
            supplier_no = setSupplierNo(ComboBox_supplier_no.Text),
            command_value = TextBox_command_value.Text,
            description = TextBox_description.Text,
            machine_port = Convert.ToInt32(TextBox_machine_port.Text),
            cnc_num = Convert.ToInt32(TextBox_cnc_num.Text)
        }) > 0)
        {
            MessageBox.Show("保存成功");
 
        }
        else
        {
            MessageBox.Show("保存失败");
        }
        }else
        if (controlCommandDal.Update(new ControlCommand()
        {
            id = parent_id,
            machine_no = TextBox_machine_no.Text,
            machine_name = TextBox_machine_name.Text,
            machine_address = TextBox_machine_address.Text,
            command_param = TextBox_command_param.Text,
            supplier_no = setSupplierNo(ComboBox_supplier_no.Text),
            command_value = TextBox_command_value.Text,
            description = TextBox_description.Text,
            machine_port = Convert.ToInt32(TextBox_machine_port.Text),
            cnc_num = Convert.ToInt32(TextBox_cnc_num.Text),
        }) > 0)
        {
            MessageBox.Show("保存成功");
           // this.Close();
        }
        else
        {
            MessageBox.Show("保存失败");
        }
        }

        private void Btn_Connect_Click(object sender, EventArgs e)
        {
            // 检查是否已经连接
            if (IsConnected()) // 需要实现这个方法来检查连接状态
            {
                MessageBox.Show("已经建立连接，请勿重复连接");
                return;
            }

            // bool res = this.mill.Connect(this.TextBox_machine_address.Text, Convert.ToInt32(this.TextBox_machine_port.Text), Convert.ToInt32(this.txtCNCNum.Text));
            bool res = this.millWrapper.Connect(this.TextBox_machine_address.Text, Convert.ToInt32(this.TextBox_machine_port.Text), Convert.ToInt32(this.TextBox_cnc_num.Text));
            if (res)
            {
                MessageBox.Show("连接成功");
            }
            else
            {
                MessageBox.Show("连接失败");
            }
            SetCtrlStatus(res);
        }

        private void SetCtrlStatus(bool bConnectSts)
        {
            if (bConnectSts)
            {
                labelShow.Text = "已连接";
            }
            else
            {
                labelShow.Text = "未连接";
     
            }
  
        }

        private bool IsConnected()
        {
            return this.millWrapper.IsConnected;
        }

        private void Button_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Control_commd_diao_Form_Load(object sender, EventArgs e)
        {
            this.Width = 600;
            this.Height = 500;

            if (parent_id == 0)
            {
                this.TextBox_machine_port.Text = "502";
                this.TextBox_cnc_num.Text = "305419896";
            }
            Query(parent_id);


        }

        private void Btn_exec_Click(object sender, EventArgs e)
        {
            int param = Int32.Parse(this.TextBox_command_param.Text);

            float para1 = float.Parse(this.TextBox_command_value.Text);

            if (IsConnected()) 
            {
                bool res = this.millWrapper.SetRVal(param, para1);
                if (res)
                {
                    MessageBox.Show("执行成功");
                }
                else
                {
                    this.millWrapper.DisConnect();
                    MessageBox.Show("执行失败");
                }
            }

        }

        /// <summary>
        /// 从主页面发起连接并执行命令的方法
        /// </summary>
        /// <param name="machineAddress">机器地址</param>
        /// <param name="commandParam">命令参数</param>
        /// <param name="commandValue">命令值</param>
        /// <returns>操作是否成功</returns>
        public bool ConnectAndExecuteCommand_jiatie(string machineAddress, int machinePort, int cncNum, string commandParam, string commandValue)
        {
            // 参数验证（参考 Control_commd_diao_Form 的做法）
            if (string.IsNullOrEmpty(machineAddress) ||
                string.IsNullOrEmpty(commandParam) ||
                string.IsNullOrEmpty(commandValue))
            {
                return false;
            }

            try
            {
                // bool res = this.mill.Connect(this.TextBox_machine_address.Text, Convert.ToInt32(this.TextBox_machine_port.Text), Convert.ToInt32(this.txtCNCNum.Text));
               // bool res = this.millWrapper.Connect(this.TextBox_machine_address.Text, Convert.ToInt32(this.TextBox_machine_port.Text), Convert.ToInt32(this.TextBox_cnc_num.Text));

                // 建立连接（参考 Control_commd_diao_Form 的连接逻辑）
                bool isConnected = this.millWrapper.Connect(
                    machineAddress,
                    machinePort,
                    cncNum
                );

                if (!isConnected)
                {
                    return false;
                }

                // 执行命令（参考 Control_commd_diao_Form 的执行逻辑）
                int param = Int32.Parse(commandParam);
                float para1 = float.Parse(commandValue);
                bool result = this.millWrapper.SetRVal(param, para1);

                // 根据执行结果决定是否断开连接
                if (!result)
                {
                    this.millWrapper.DisConnect();
                }

                return result;
            }
            catch (Exception ex)
            {
                // 异常处理（参考 Control_commd_diao_Form 的做法）
                Console.WriteLine($"ConnectAndExecuteCommand 异常: {ex.Message}");
                this.millWrapper.DisConnect();
                return false;
            }
        }

    }
}
